<?php

namespace App\Events;

use App\Master\Framework\Extend\Core;
use App\Models\Admin\Framework\AdminAccessLogModel;
use App\Models\Admin\Framework\AdminMenusModel;
use App\Utils\Common;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Http\Request;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;


class AdminAccessEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    protected $crumb = [];

    /**
     * Create a new event instance.
     *
     * @param array $params
     * @return bool
     */
    public function __construct()
    {
//        if (request()->isMethod('get')) {
//            return true;
//        }
        if (!Auth::guard('admin')->user()->is_show) {
            return true;
        }
        $input      = request()->input();
        $domain     = Common::getHttp();
        $source_url = (isset($input['_url']) && $input['_url']) ? str_replace($domain, '', $input['_url']) : Request::capture()->getPathInfo();
        $prefix     = config('admin.prefix');
        $menusUrl   = str_replace("/{$prefix}/", '', $source_url);
        if (in_array($menusUrl,['framework/setup/pageUpdateSetup','framework/setup/pageGetSetup'])){
            $menusUrl = explode("/{$prefix}/",$_SERVER['HTTP_REFERER']);
            $menusUrl = $menusUrl[1] ?? '';
        }
        if (!$menus = AdminMenusModel::query()->select(['id', 'parent_id', 'name'])->where(['path' => $menusUrl])->first()) {
            return true;
        }

        $this->recursionCrumb($menus->parent_id);
        usleep(2000);
        $this->crumb[]         = $menus->name;
        $inserts['user_id']    = Auth::guard('admin')->user()->id ?? 0;
        $inserts['account']    = Auth::guard('admin')->user()->account ?? '';
        $inserts['path']       = Request::capture()->getPathInfo();
        $inserts['ip']         = $_SERVER['HTTP_X_REAL_IP'] ?? Request::capture()->getClientIp();
        $inserts['created_at'] = time();
        $inserts['menu_path']  = implode('/', $this->crumb);
        $inserts['method']     = request()->method();
        $inserts['browser']    = (new Agent())->browser();
        $inserts['region']     = Core::getIpRegion($inserts['ip']);
        $inserts['action']     = $menus->name;
        $inserts['params']     = json_encode($input, JSON_UNESCAPED_UNICODE);
        $inserts['result']     = json_encode([], JSON_UNESCAPED_UNICODE);

        $admin_request_id = AdminAccessLogModel::query()->insertGetId($inserts);

        defined('ADMIN_REQUEST_ID') or define('ADMIN_REQUEST_ID', $admin_request_id);

        return true;
    }


    protected function recursionCrumb($menu_id)
    {

        if (!$menus = AdminMenusModel::query()->select(['id', 'parent_id', 'name'])->where(['id' => $menu_id])->first()) {
            return $this->crumb;
        }
        array_unshift($this->crumb, $menus->name);
        if ($menus->parent_id) {
            $this->recursionCrumb($menus->parent_id);
        } else {
            return $this->crumb;
        }
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
